package xyz.iguilty.workflow.core.service.impl;

import org.flowable.engine.HistoryService;
import org.flowable.engine.IdentityService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.idm.api.Group;
import org.flowable.idm.api.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import xyz.iguilty.workflow.core.service.WorkFlowIdentityService;
import xyz.iguilty.workflow.model.SimpleGroup;
import xyz.iguilty.workflow.model.SimpleUser;

import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

@Service
public class FlowableIdentityService implements WorkFlowIdentityService {
    @Autowired
    private IdentityService identityService;
    @Autowired
    private HistoryService historyService;
    @Override
    public void saveUser(String userId, String displayName) {
        User user = identityService.newUser(userId);
        user.setDisplayName(displayName);
        identityService.saveUser(user);
    }

    @Override
    public SimpleUser getUser(String userId) {
        User user = identityService.createUserQuery().userId(userId).singleResult();
        return user==null?null:new SimpleUser(user.getId(),user.getDisplayName());
    }

    @Override
    public List<SimpleUser> listUser(List<String> userIds) {
        List<User> list = identityService.createUserQuery().userIds(userIds).list();
        if (!CollectionUtils.isEmpty(list)){
            return list.stream().map(user -> new SimpleUser(user.getId(),user.getDisplayName())).collect(Collectors.toList());
        }else {
            return null;
        }
    }

    @Override
    public List<SimpleUser> listUser(String groupId) {
        List<User> list = identityService.createUserQuery().memberOfGroup(groupId).list();
        if (!CollectionUtils.isEmpty(list)){
            return list.stream().map(user -> new SimpleUser(user.getId(),user.getDisplayName())).collect(Collectors.toList());
        }else {
            return null;
        }
    }

    @Override
    public String getUserDisplayNameChain(List<String> userIds) {
        List<User> list = identityService.createUserQuery().userIds(userIds).list();
        if (!CollectionUtils.isEmpty(list)) {
            StringJoiner stringJoiner =new StringJoiner(",");
            list.forEach(user -> stringJoiner.add(user.getDisplayName()));
            return stringJoiner.toString();
        }
        return null;
    }

    @Override
    public void deleteUser(String userId) {
        identityService.deleteUser(userId);
    }

    @Override
    public void saveGroup(String groupId, String displayName) {
        Group group = identityService.newGroup(groupId);
        group.setName(displayName);
        group.setType("10");//默认10待表角色 其它暂不考虑
        identityService.saveGroup(group);
    }

    @Override
    public SimpleGroup getGroup(String groupId) {
        Group group = identityService.createGroupQuery().groupId(groupId).singleResult();
        return group==null?null:new SimpleGroup(group.getId(),group.getName());
    }

    @Override
    public List<SimpleGroup> listGroup(List<String> groupIds) {
        List<Group> list = identityService.createGroupQuery().groupIds(groupIds).list();
        if (!CollectionUtils.isEmpty(list)){
            return list.stream().map(group -> new SimpleGroup(group.getId(), group.getName())).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public String getGroupDisplayNameChain(List<String> groupIds) {
        List<Group> list = identityService.createGroupQuery().groupIds(groupIds).list();
        if (!CollectionUtils.isEmpty(list)) {
            StringJoiner stringJoiner =new StringJoiner(",");
            list.forEach(group -> stringJoiner.add(group.getName()));
            return stringJoiner.toString();
        }
        return null;
    }

    @Override
    public void deleteGroup(String groupId) {
        identityService.deleteGroup(groupId);
    }

    @Override
    public void createMembership(String userId, String groupId) {
        identityService.createMembership(userId,groupId);
    }

    @Override
    public void deleteMemberShip(String userId, String groupId) {
        identityService.deleteMembership(userId,groupId);
    }

    @Override
    public void setAuthenticatedUserId(String userId) {
        identityService.setAuthenticatedUserId(userId);
    }

    @Override
    public SimpleUser getStarter(String processInstanceId) {
        if (processInstanceId == null) {
            throw new IllegalArgumentException("请输入流程实例id");
        }
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        if (historicProcessInstance != null) {
            String startUserId = historicProcessInstance.getStartUserId();
            if (startUserId != null) {
                return this.getUser(startUserId);
            }
        }
        return null;
    }
}
